package com.cedifie.lendapp.ui.steps.fm

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.FmStepCommonBinding
import com.cedifie.lendapp.http.ApiService.addCommonParams
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.ui.steps.act.CedStepAct
import com.cedifie.lendapp.ui.steps.adapter.CedStepCommonAdapter
import com.cedifie.lendapp.utils.decoration.LinearSpacingItemDecoration
import com.cedifie.lendapp.utils.dialog.StepCommonPopup
import com.cedifie.lendapp.utils.event.CedEventManager
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lib_baseadapter.CEDOnItemChildClickListener
import com.cedifie.pickerview.builder.TimePickerBuilder
import com.cedifie.pickerview.listener.OnTimeSelectListener
import com.cedifie.pickerview.view.TimePickerView
import com.lib.base.base.BaseFragment
import com.lib.base.utils.DensityUtils
import com.lib.base.utils.log.LogHelper
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/18 14:46
 * @Annotation：流程通用列表样式
 */
class CedStepCommonFm(): BaseFragment() {
    private var _binding: FmStepCommonBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )
    private var data: JSONObject? = null

    //内容列表
    var mCommonAdapter: CedStepCommonAdapter? = null
    var mSelectPosition = -1

    //出生日期选择
    private var pvStartDateView: TimePickerView? = null

    constructor(data: JSONObject): this(){
        this.data = data
    }

    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmStepCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.transparent))
        initRecyclerView()
    }

    override fun initCedListener() {
        //下一步
        _binding?.btnNext?.setOnClickListener {
            _binding?.root?.clearFocus()
            if (!isAllowSubmit()){
                showCedToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }
            data?.let {
                val params = JSONObject().addCommonParams().apply {
                    put("path",it.optString("apiUrl").replace("/",""))
                }
                mCommonAdapter?.let { adapter ->
                    for (i in 0..< adapter.itemCount){
                        val item = adapter.getItem(i)
                        if (item.has("selectItem")){
                            val selectItem = item.optJSONObject("selectItem")
                            if (selectItem != null){
                                params.put(item.optString("paramName"),selectItem.optString("value"))
                            }
                        }
                    }
                }
                HttpHelper.addCedEventAction(String.format(CedEventType.CLICK.CED_CLICK_STEP_XX_NEXT,it.optString("stepTitle")),"")
                //立即上报
                CedEventManager.getInstance().updateCedEventsNow()

                LogHelper.e(">>>>>>submit data >>>>>>>$params")
                val act = context as CedStepAct
                act.onSubmitProcessAction(params)
            }
        }
    }

    override fun initCedData() {
        val dataList = arrayListOf<JSONObject>()
        if (data != null){
            val stepTitle = data?.optString("stepTitle","")
            _binding?.layoutPersonalTips?.visibility = View.GONE
            if (stepTitle == "personal_info"){
                val showKey = getString(R.string.process_personal_info_tips_key)
                val showText = String.format(getString(R.string.process_personal_info_tips),showKey)
                val startIndex = showText.indexOf(showKey)
                val dataSecuritySpannable = SpannableString(showText)
                dataSecuritySpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF3263B0")), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                _binding?.tvPersonalTips?.text = dataSecuritySpannable
                _binding?.layoutPersonalTips?.visibility = View.VISIBLE
            }

            HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_COMMON_XX_START,stepTitle),"")
            val dataArray = data?.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..<dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
            }
        }
        mCommonAdapter?.data = dataList
    }

    /**
     * 初始化页面内容列表
     */
    private fun initRecyclerView() {
        _binding?.recyclerView?.setHasFixedSize(true)
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.recyclerView?.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        _binding?.recyclerView?.addItemDecoration(LinearSpacingItemDecoration(0,0,0,topDecoration))
        mCommonAdapter = CedStepCommonAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = mCommonAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        mCommonAdapter?.setOnItemChildClickListener(onItemClickListener)
    }

    /**
     * 选择
     */
    private val onItemClickListener = CEDOnItemChildClickListener { parent, childView, position ->
        _binding?.root?.clearFocus()
        mSelectPosition = position
        mCommonAdapter?.let {
            val item = it.getItem(position)
            when(item.optString("action")){
                "DATE_PICK" -> {//时间选择
                    showBirthDialog()
                }
                "SELECT"->{//选择
                    val dataList = arrayListOf<JSONObject>()
                    val dataArray = item.optJSONArray("values")
                    for (i in 0..<dataArray.length()){
                        dataList.add(dataArray.optJSONObject(i))
                    }
                    showSelectPopupwindow(childView,dataList)
                }
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        val selectPopup = StepCommonPopup(requireContext())
        selectPopup.setWindowWidth(view.width + DensityUtils.dp2px(10f))
        selectPopup.setSelectItemListener(object : StepCommonPopup.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                mCommonAdapter?.let { adapter ->
                    val item = adapter.getItem(mSelectPosition)
                    item.put("selectItem",data)
                    adapter.notifyItemChanged(mSelectPosition)

                    data?.let {
                        val subRemark = "${it.optString("value")}$$${it.optString("duration")}"
                        HttpHelper.addCedEventAction(String.format(CedEventType.CLICK.CED_CLICK_STEP_XX_SELECT,item.optString("paramName")), subRemark)
                    }
                }
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        _binding?.let {
            selectPopup.show(view, it.root)
            selectPopup.setBrandList(dataList)
        }
    }

    /**
     * 选择出生日期
     */
    var startTime = 0L
    private fun showBirthDialog(){
        //开始选择时间
        startTime = System.currentTimeMillis()
        if(pvStartDateView == null){
            //时间可选范围18-100岁
            //当前日期
            val curtDate = Calendar.getInstance()
            val startDate = Calendar.getInstance()
            startDate.timeInMillis = curtDate.timeInMillis
            startDate.add(Calendar.YEAR,-100)

            val endDate = Calendar.getInstance()
            endDate.timeInMillis = curtDate.timeInMillis
            endDate.add(Calendar.YEAR,-18)

            pvStartDateView = TimePickerBuilder(context, object : OnTimeSelectListener {
                override fun onTimeSelect(date: Date?, v: View?) {
                }

                @SuppressLint("SimpleDateFormat")
                override fun onTimeSelectString(date: Date, showDate: String) {
                    val value = SimpleDateFormat("yyyy-MM-dd").format(date)
                    //可根据需要自行截取数据显示
                    mCommonAdapter?.let {
                        val item = it.getItem(mSelectPosition)
                        val obj = JSONObject()
                        obj.put("title",showDate)
                        obj.put("value",value)
                        item.put("selectItem",obj)
                        it.notifyItemChanged(mSelectPosition)

                        val subRemark = "${value}$$${System.currentTimeMillis() - startTime}"
                        HttpHelper.addCedEventAction(String.format(CedEventType.CLICK.CED_CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                    }
                }
            })
                .setDate(endDate) //默认选中
                .setRangDate(startDate, endDate) //可选择时间范围
                .setLayoutRes(R.layout.dialog_birth) { v ->
                    val ivClose = v?.findViewById<ImageView>(R.id.ivClose)
                    ivClose?.setOnClickListener {
                        pvStartDateView?.dismiss()
                    }
                    //确定
                    val btnDone = v?.findViewById<TextView>(R.id.btnDone)
                    btnDone?.setOnClickListener {
                        pvStartDateView?.returnData()
                        pvStartDateView?.dismiss()
                    }
                }
                .isDialog(true)
                .setContentTextSize(16)
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("", "", "", "", "", "")
                .setLineSpacingMultiplier(3f)
                .setTextXOffset(40, 40, 40, 40, 40, 40)
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTextColorCenter(Color.parseColor("#FF08252C")) //设置选中项文字颜色
                .setTextColorOut(Color.parseColor("#FF9CA8AB"))//默认颜色
                .setContentTextSize(16)
                .isAlphaGradient(true)
                .setItemVisibleCount(3)
                .isCyclic(true)
                .setDividerColor(ContextCompat.getColor(requireContext(), R.color.transparent))
                .build()
            val dialog = pvStartDateView?.dialog
            if (dialog != null){
                val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)
                params.leftMargin = 0
                params.rightMargin = 0
                pvStartDateView?.dialogContainerLayout?.setLayoutParams(params)
                val dialogWindow = dialog.window
                if (dialogWindow != null) {
                    dialogWindow.setWindowAnimations(com.cedifie.pickerview.R.style.picker_view_scale_anim) //修改动画样式
                    dialogWindow.setGravity(Gravity.CENTER)
                    dialogWindow.setDimAmount(0.3f)
                }
            }
        }
        pvStartDateView?.show()
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        mCommonAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                //存在 isMust && isMust == ”NO“  非必填
                if (item.has("isMust") && item.optString("isMust") == "NO"){
                    continue
                }
                //必填 && 没有内容 || 内容为空
                if (!item.has("selectItem")){
                    isAllow = false
                    break
                }
                val selectItem = item.optJSONObject("selectItem")
                if (selectItem == null){
                    isAllow = false
                    break
                }
                if (selectItem.optString("value").isEmpty()){
                    isAllow = false
                    break
                }
            }
        }
        return isAllow
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (data != null){
            HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_COMMON_XX_END,data?.optString("stepTitle")),"")
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}